import React, { useState } from 'react';

const LotteryGrid = () => {
  const [isSpinning, setIsSpinning] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(-1);
  const [result, setResult] = useState(null);

  // 奖品配置
  const prizes = [
    { id: 0, name: '一等奖', desc: 'iPhone 17', probability: 0.01 },
    { id: 1, name: '二等奖', desc: 'iPad', probability: 0.05 },
    { id: 2, name: '三等奖', desc: 'AirPods', probability: 0.1 },
    { id: 3, name: '四等奖', desc: '购物券', probability: 0.2 },
    { id: 4, name: '五等奖', desc: '优惠券', probability: 0.3 },
    { id: 5, name: '六等奖', desc: '积分', probability: 0.34 },
    { id: 6, name: '谢谢参与', desc: '再来一次', probability: 0 },
    { id: 7, name: '谢谢参与', desc: '再来一次', probability: 0 }
  ];

  // 抽奖逻辑
  const startLottery = () => {
    if (isSpinning) return;
    
    setIsSpinning(true);
    setResult(null);
    
    // 随机选择中奖结果
    const random = Math.random();
    let winIndex = 6; // 默认谢谢参与
    let cumulative = 0;
    
    for (let i = 0; i < prizes.length; i++) {
      cumulative += prizes[i].probability;
      if (random <= cumulative) {
        winIndex = i;
        break;
      }
    }
    
    // 模拟转动效果
    let spins = 0;
    const maxSpins = 20 + Math.floor(Math.random() * 10);
    
    const spinInterval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % 8);
      spins++;
      
      if (spins >= maxSpins) {
        clearInterval(spinInterval);
        setCurrentIndex(winIndex);
        setResult(prizes[winIndex]);
        setIsSpinning(false);
      }
    }, 100);
  };

  return (
    <div className="lottery-grid">
      <div className="grid-container">
        {prizes.map((prize, index) => (
          <div
            key={index}
            className={`grid-item ${currentIndex === index ? 'active' : ''}`}
          >
            <div className="prize-name">{prize.name}</div>
            <div className="prize-desc">{prize.desc}</div>
          </div>
        ))}
      </div>
      
      <div className="lottery-controls">
        <button 
          className={`lottery-btn ${isSpinning ? 'spinning' : ''}`}
          onClick={startLottery}
          disabled={isSpinning}
        >
          {isSpinning ? '抽奖中...' : '开始抽奖'}
        </button>
      </div>
      
      {result && (
        <div className="lottery-result">
          <h3>恭喜您获得：{result.name}</h3>
          <p>{result.desc}</p>
        </div>
      )}
    </div>
  );
};

export default LotteryGrid;